package com.briup.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.reggie.common.CustomException;
import com.briup.reggie.dto.DishDto;
import com.briup.reggie.entity.*;
import com.briup.reggie.mapper.DishMapper;
import com.briup.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品，同时保存菜品对应的口味数据
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本信息到dish表
        this.save(dishDto);
        //获取菜品id
        Long dishId = dishDto.getId();

        //对菜品口味数据进行完善，因为传过来的数据只有name和value，缺少关联的菜品id，需要加上
        List<DishFlavor> flavors = dishDto.getFlavors();
        //stream流
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味表到dish_flavor
        dishFlavorService.saveBatch(flavors);

        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
    }

    /**
     * dish分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<DishDto> dtoPage(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.like(name!=null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        this.page(pageInfo,queryWrapper);

        //对象拷贝,这里拷贝分页条数据总条数，第几页，每页展示多少条数据
        //注意：
        //这里忽略了MyBatis-plus里分页中的records属性(也就是展示页面数据这个属性，由后面的专门操作进行)
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        //为了给列表添加一个菜品分类数据
        //1.获取菜品（Dish）列表
        List<Dish> records = pageInfo.getRecords();
        //2.遍历，给每个数据加上菜品分类名称
        List<DishDto> list = records.stream().map((item)->{
            //拷贝菜品基础属性
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                //将菜品分类名称赋值给dishDto列表
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //设置页面列表，这里面就含有了菜品分类名称属性
        dishDtoPage = dishDtoPage.setRecords(list);

        return dishDtoPage;
    }

    /**
     * 根据id查询菜品，及其对应口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息，从dish中查
        Dish dish = this.getById(id);

        //把dish基本信息拷贝到dishDto中
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //查询菜品对应口味，从dish_flavor中查
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(DishFlavor::getDishId,id);
        //执行查询
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        //最后单独添加上对应口味信息
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    /**
     * 修改菜品信息
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        this.updateById(dishDto);
        //清理当前菜品对应口味数据dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //重新添加当前菜品对应口味数据dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        //stream流,(因为缺少id，所以要遍历去添加id后再传入)
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
    }

    /**
     * 删除/批量删除操作
     * @param ids
     */
    @Override
    @Transactional
    public void deleteWithFlavor(List<Long> ids) {
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getDishId, id);
            int count = setmealDishService.count(queryWrapper);
            if (count>0){
                throw new CustomException("当前菜品关联了套餐无法删除");
            }
        }
        for (Long id : ids) {
            //清除redis当中的缓存
            Dish dish = this.getById(id);
            String key = "dish_" + dish.getCategoryId() + "_1";
            redisTemplate.delete(key);

            //清理菜品关联的口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(queryWrapper);
        }

        //清理菜品基本信息
        this.removeByIds(ids);
    }

    /**
     * 起售与停售
     * @param status
     * @param ids
     */
    @Override
    public void setStatus(Integer status, List<Long> ids) {
        Dish dish = new Dish();
        for (Long dishId : ids) {
            dish.setId(dishId);
            dish.setStatus(status);
            this.updateById(dish);

            //清除redis当中的缓存
            Dish dishById = this.getById(dishId);
            String key = "dish_"+dishById.getCategoryId()+"_1";
            redisTemplate.delete(key);
        }
    }

    /**
     * 查询菜品列表
     * （套餐想要包含哪些菜品）
     * @return
     */
    /*@Override
    public List<Dish> list(Dish dish) {
        Long categoryId = dish.getCategoryId();
        //构造
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件和排序条件
        queryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        //查询菜品还在起售的，status为1
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = this.list(queryWrapper);
        return list;
    }*/

    @Override
    public List<DishDto> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList!=null){
            //如果存在，直接返回，无需查询数据库
            return dishDtoList;
        }

        //构造
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件和排序条件
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //查询菜品还在起售的，status为1
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = this.list(queryWrapper);

        //2.遍历，给每个数据加上菜品分类名称和口味信息
        dishDtoList = list.stream().map((item)->{
            //拷贝菜品基础属性
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                //将菜品分类名称赋值给dishDto列表
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在，查询数据库，将查到的菜品缓存到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return dishDtoList;
    }
}
